﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using OpenFileDialog = CustomDrawnFileDialog.CustomFileDialog;
using System.Diagnostics;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Net;

using CustomDrawnFileDialog;

using LowLevelGraphics;
using LowLevelGraphics.Filter;
using LowLevelGraphics.Extractors;
using LowLevelGraphics.Analysis;
using LowLevelGraphics.Histograms;
using ImageRecognition2.Forms;
using System.Reflection;

namespace ImageRecognition2
{
    public class Helper
    {
        /// <summary>
        /// Opens a decodable file dialog
        /// </summary>
        /// <param name="bUseNormalFile"></param>
        /// <returns></returns>
        public static IFileDialog OpenDecodableFileDialog(bool bUseNormalFile)
        {
            if (bUseNormalFile)
            {
                IFileDialog fd = new OpenFileDialogWrapper();
                return fd;
            }
            else
            {
                ICustomFileDialog fd = (ICustomFileDialog)new OpenFileDialog();

                fd.Filter = "Picture files (*.JPG;*.GIF;*.PNG)\0*.jpg;*.gif;*.png\0Alle Dateien (*.*)\0\0";
                fd.SelectionChanged += new CustomDrawnFileDialog.SelectionChangedEventHandler(MainFormSingleton.Instance.ofd_SelectionChanged);
                return fd;
            }
        }

        public static void Test5()
        {
            UnsafeBitmap _bitmap = (Bitmap)MainFormSingleton.ActivePictureBox.BackgroundImage;
            Point pt1 = _bitmap.GetCoordinatesFromIndex(7);
            Point pt2 = _bitmap.GetCoordinatesFromIndex(8);
            //Histogram histogram = new Histogram(_bitmap);
            //UnsafeBitmap bitmap = new UnsafeBitmap(_bitmap);
            ////new OutlineContours().Execute(bitmap);

            //int nRedEnergy = histogram.PureRedEnergy;
            //int nGreenEnergy = histogram.PureGreenEnery;
            //int nBlueEnergy = histogram.PureBlueEnergy;

            //if (nRedEnergy > nGreenEnergy && nRedEnergy > nBlueEnergy) { }
            //if (nGreenEnergy > nRedEnergy && nGreenEnergy > nBlueEnergy) { }
            //if (nBlueEnergy > nRedEnergy && nBlueEnergy > nGreenEnergy) { }

            //if (nRedEnergy > nBlueEnergy && nGreenEnergy > nBlueEnergy) { }
            //if (nRedEnergy > nGreenEnergy && nBlueEnergy > nGreenEnergy) { }
            //if (nGreenEnergy > nRedEnergy && nBlueEnergy > nRedEnergy) { }

            //int nHeight = bitmap.Height;
            //int nWidth = bitmap.Width;
            //for (int y = 0; y < bitmap.Height; y++)
            //{
            //    for (int x = 0; x < bitmap.Width; x++)
            //    {

            //    }
            //}
            //bitmap.Dispose();

            new GrayScale(GRAYSCALE.GRAYSCALE_MEDIAN).Execute(_bitmap);
            MainFormSingleton.ActivePictureBox.Invalidate();
        }

        public static void Test6()
        {
            Bitmap _bitmap = (Bitmap)MainFormSingleton.ActivePictureBox.BackgroundImage;
            //new RecolorizeColorSpace(typeof(HunterLab)).Execute(bitmap);
            //new Normalize(Normalize_Mode.YUV).Execute(bitmap);

            //bitmap = BitmapFunctions.AutoCrop(bitmap);
            //bitmap = new AutoCrop().Crop(bitmap);

            UnsafeBitmap bitmap = new UnsafeBitmap(_bitmap);
            List<Color> aColor = new List<Color>();

            int x = 0;
            int y = 0;

            int nHeight = bitmap.Height;
            int nWidth = bitmap.Width;
            for (y = 0; y < nHeight; y++)
            {
                aColor.Clear();
                aColor.Add(bitmap.GetPixel(x, y));
                for (x = 1; x < nWidth; x++)
                {
                    aColor.Add(bitmap.GetPixel(x, y));
                    Color color1 = aColor[x];
                    Color color2 = aColor[x - 1];

                    if (Math.Abs(ColorFunctions.Distance(color1, color2) - (int)ColorFunctions.MaxDistance()) < 200)
                    {
                        bitmap.SetPixel(x, y, Color.White);
                    }
                    else
                    {
                        bitmap.SetPixel(x, y, Color.Black);
                    }
                }
            }
            bitmap.Dispose();
            MainFormSingleton.ActivePictureBox.Invalidate();
        }

        public static void ColorBlobExtractor()
        {
            UnsafeBitmap bitmap = MainFormSingleton.ActivePictureBox.BackgroundImage;

            Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
            int[] aVec = new int[5];
            int[] aVec2 = new int[5];
            int i = 0;

            //OutlineContours filter = new OutlineContours();
            //filter.UseDefaultMode = false;
            //filter.Execute(MainFormSingleton.ActivePictureBox.BackgroundImage).UnlockImage();

            //BaseImageFilter filter = new AdaptiveThresholding(THRESHOLDING_MODE.OWN_METHOD2, 0, 10);
            //filter.Execute(MainFormSingleton.ActivePictureBox.BackgroundImage).UnlockImage();

            //DetermineBoundingBox();
            //CovarianceMatrix m = new CovarianceMatrix();
            //m.Calc();

            Color color1 = Color.Transparent;
            Color color2 = Color.Transparent;

            //int nR = 0;
            //int nG = 0;
            //int nB = 0;

            //Image image = MainFormSingleton.ActivePictureBox.BackgroundImage;
            //Segmentator s = new Segmentator(image, 10, 10, 10);
            //s.FastSegmentation();

            //Size size = image.Size;

            //UnsafeBitmap bitmap1 = BitmapFunctions.GetPicturePart(image, new Rectangle(0, 0, size.Width / 2, size.Height));
            //UnsafeBitmap bitmap2 = BitmapFunctions.GetPicturePart(image, new Rectangle(size.Width / 2, 0, size.Width, size.Height));

            //if (BitmapFunctions.CompareByPixelUnsafe(bitmap1, bitmap2))
            //{
            //    MessageBox.Show("Those bitmaps are equal! No comparison will take place!");
            //    return;
            //}


            //new Distance().Process(bitmap1, bitmap2).UnlockImage();
            //MainFormSingleton.ActivePictureBox.Invalidate();

            //new diff().Execute(bitmap).UnlockImage();

            //new Clean().Execute(bitmap).UnlockImage();
            //new OwnOptimizedConvolutionDouble(0, 1,
            //    new double[,]{
            //        {1,2,3,4,5},
            //        {-1,-2,-3,-4,-5},
            //        {1,1,1,1,1},
            //        {-1,-1,-1,-1,-1},
            //        {0,0,0,0,0}
            //        }).Execute(
            //        bitmap).UnlockImage();

            //for (y = 0; y < nHeight; y++)
            //{
            //    for (x = 0; x < nWidth-1; x++)
            //    {
            //        //color1 = bitmap.GetPixel(x, y);
            //        //color2 = bitmap.GetPixel(x + 1, y);
            //        //bool bWhite = ColorFunctions.DistanceSquared(color1, color2) > 14000;
            //        //    nR = Math.Abs(color1.R - color1.G);
            //        //    nG = Math.Abs(color1.G - color1.B);
            //        //    nB = Math.Abs(color1.B - color1.R);
            //        //    bWhite &= (nR + nG + nB) < 20;

            //        //    nR = Math.Abs(color2.R - color2.G);
            //        //    nG = Math.Abs(color2.G - color2.B);
            //        //    nB = Math.Abs(color2.B - color2.R);

            //        //    bWhite |= (nR + nG + nB) < 20;

            //        bool bWhite = new DoubleInterval(67, 72).Contains(new HunterLab(bitmap.GetPixel(x, y)).L);
            //        bitmap.SetPixel(x, y, bWhite ? Definitions.White : Definitions.Black);
            //    }
            //}
            //bitmap.UnlockImage();

            MainFormSingleton.ActivePictureBox.Invalidate();

            //PerPixelFilter p = new PerPixelFilter(
            //    delegate(Color _color)
            //    {
            //        YCbCr ycbcr = new YCbCr(_color);
            //        if (new DoubleInterval(72, 99).Contains(ycbcr.Y)
            //            && new DoubleInterval(0.2, 2.8).Contains(ycbcr.Cb)
            //            && new DoubleInterval(5, 9).Contains(ycbcr.Cr))
            //        {
            //            return Definitions.White;
            //        }
            //        else
            //        {
            //            return Definitions.Black;
            //        }
            //    });

            //p.Execute(MainFormSingleton.ActivePictureBox.BackgroundImage).Dispose();

            //MainFormSingleton.ActivePictureBox.Invalidate();
        }

        public static string GetInsertStatementFromFilter(IFilter filter)
        {
            PropertyInfo[] aInfo = filter.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

            string sParam = string.Empty;
            foreach (PropertyInfo info in aInfo)
            {
                object oValue = info.GetValue(filter, null);
                sParam += string.Format("{0}={1}", info.Name, oValue) + " ";
            }

            string sCommandString = string.Format("{0} {1}", filter.GetType().Name, sParam);
            return sCommandString;
        }

        /// <summary>
        /// Creates the syntax string.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns></returns>
        public static string CreateSyntaxString(Type type)
        {
            string sTest = type.Name + " (";
            foreach (ConstructorInfo constructorInfo in type.GetConstructors())
            {
                foreach (ParameterInfo p in constructorInfo.GetParameters())
                {
                    sTest += string.Format("{0} {1}", p.ParameterType.FullName, p.Name) + ",";
                }
            }
            sTest = sTest.TrimEnd(',');
            sTest += " )";

            return sTest;
        }

        public static void SimpleBlobExtractor()
        {
            UnsafeBitmap bitmap = MainFormSingleton.ActivePictureBox.BackgroundImage;

            BlobExtractor be = new BlobExtractor(bitmap);
            Blob[] aBlob = be.Detect();

            Color[] aColor = new Color[] { Definitions.Black, Definitions.Gray, Definitions.Green, Definitions.Red, Definitions.Yellow, Definitions.Magenta, Definitions.Cyan, Definitions.Blue };
            int nIndex = 0;

            int nColorLength = aColor.Length;
            foreach (Blob blob in aBlob)
            {
                if (blob == null) continue;
                nIndex++;
                nIndex %= nColorLength;

                foreach (Point point in blob.Points)
                {
                    bitmap.SetPixel(point, aColor[nIndex]);
                }
            }
            bitmap.UnlockImage();

            MainFormSingleton.ActivePictureBox.Invalidate();
        }

        public static void ExtractAnaglyph()
        {
            Image image = MainFormSingleton.ActivePictureBox.BackgroundImage;
            Size size = image.Size;

            UnsafeBitmap bitmap1 = BitmapFunctions.GetPicturePart(image, new Rectangle(0, 0, size.Width / 2, size.Height));
            UnsafeBitmap bitmap2 = BitmapFunctions.GetPicturePart(image, new Rectangle(size.Width / 2, 0, size.Width, size.Height));

            Anaglyph anaglyph = new Anaglyph();
            anaglyph.Mode = AnaglyphMode.Optimized;
            UnsafeBitmap bitmapResult = anaglyph.Process(bitmap1, bitmap2);
            bitmapResult.UnlockImage();
            MainFormSingleton.ActivePictureBox.BackgroundImage = bitmapResult.InternalBitmap;
        }

        /// <summary>
        /// Analyse
        /// </summary>
        public static void Analyse()
        {
            Bitmap bitmap = (Bitmap)MainFormSingleton.ActivePictureBox.BackgroundImage;
            DrawPixelColorDependencyLine drawPixelColorDependencyLine = new DrawPixelColorDependencyLine(bitmap);
            drawPixelColorDependencyLine.Analyse();
            MainFormSingleton.ActivePictureBox.Invalidate();
        }

        public static void ExtractDisparityMap()
        {
            Image image = MainFormSingleton.ActivePictureBox.BackgroundImage;
            Size size = image.Size;

            UnsafeBitmap bitmap1 = BitmapFunctions.GetPicturePart(image, new Rectangle(0, 0, size.Width / 2, size.Height));
            UnsafeBitmap bitmap2 = BitmapFunctions.GetPicturePart(image, new Rectangle(size.Width / 2, 0, size.Width, size.Height));

            DisparityMap disparityMap = new DisparityMap();
            disparityMap.MODE = DISPARITY_MAP.SAD;
            UnsafeBitmap bitmapResult = disparityMap.Process(bitmap1, bitmap2);
            bitmapResult.UnlockImage();
            MainFormSingleton.ActivePictureBox.BackgroundImage = bitmapResult.InternalBitmap;
        }

        public static void ExtractLeftRightJPS()
        {
            Image image = MainFormSingleton.ActivePictureBox.BackgroundImage;
            Size size = image.Size;

            UnsafeBitmap bitmap1 = BitmapFunctions.GetPicturePart(image, new Rectangle(0, 0, size.Width / 2, size.Height));
            UnsafeBitmap bitmap2 = BitmapFunctions.GetPicturePart(image, new Rectangle(size.Width / 2, 0, size.Width, size.Height));

            MainFormSingleton.ActivePictureBox.BackgroundImage = bitmap1.InternalBitmap;

            FormChild formChild = GuiHelper.CreateNewChild();
            MainFormSingleton.ActivePictureBox.BackgroundImage = bitmap2.InternalBitmap;

            bitmap1.Dispose();
            bitmap2.Dispose();
        }

        public static void DeAnaglyph()
        {
            UnsafeBitmap bitmap = MainFormSingleton.ActivePictureBox.BackgroundImage;
            DeAnaglyph deanaglyph = new DeAnaglyph();
            deanaglyph.Execute(bitmap).UnlockImage();

            deanaglyph.BitmapLeft.Dispose();
            deanaglyph.BitmapRight.Dispose();
            MainFormSingleton.ActivePictureBox.BackgroundImage = deanaglyph.BitmapLeft.InternalBitmap;
            FormChild formChild = GuiHelper.CreateNewChild();
            MainFormSingleton.ActivePictureBox.BackgroundImage = deanaglyph.BitmapRight.InternalBitmap;
        }

        public static void UpdateFilterList()
        {
            IEnumerable<Type> collection = Definitions.FilterList();

            StreamWriter writer = new StreamWriter(ImageRecognition2Definitions.FilterTypeStringListFile);
            foreach (Type type in collection)
            {
                writer.WriteLine(type.FullName);
            }
            writer.Close();
        }

        public static void Test4()
        {
            //Bitmap _bitmap = (Bitmap)MainFormSingleton.ActivePictureBox.BackgroundImage;
            ////new DistanceFilter().Execute(_bitmap);
            ////new Defog().Execute(_bitmap);

            //new Impainter().Restore(_bitmap);
            //MainFormSingleton.ActivePictureBox.Invalidate();
            //---------------------------------------------------------

            Bitmap mainFormSingletonActivePictureBoxBackgroundImage = (Bitmap)MainFormSingleton.ActivePictureBox.BackgroundImage;
            LowLevelGraphics.Filter.ConnectedComponents newConnectedComponents = new LowLevelGraphics.Filter.ConnectedComponents(mainFormSingletonActivePictureBoxBackgroundImage);
            newConnectedComponents.ObjectIsolation(mainFormSingletonActivePictureBoxBackgroundImage);
            /*MainFormSingleton.ActivePictureBox.BackgroundImage = mainFormSingletonActivePictureBoxBackgroundImage;
            new Backprojection().Execute(mainFormSingletonActivePictureBoxBackgroundImage).Dispose();
            MainFormSingleton.ActivePictureBox.Invalidate();*/
        }

        public static void Test3()
        {
            Bitmap _bitmap = (Bitmap)MainFormSingleton.ActivePictureBox.BackgroundImage;
            //new LowLevelGraphics.Filter.MixChannels("RG", "GB", "RB").Execute(bitmap);
            //new ImageBitShift().Execute(bitmap);

            //Bitmap bitmap1 = (Bitmap)Image.FromFile(@"D:\Temp\programmieren\Temp\11elkgrove.jpg");
            //new ImageRegistration(bitmap1,Point.Empty, new Size(2,2),false).Execute(bitmap);
            //new Circle().Execute(bitmap);

            //new WhiteColorBalance(PROCESSING_MODE.R).Execute(bitmap);

            Histogram histogram = new Histogram((Bitmap)_bitmap.Clone());
            UnsafeBitmap bitmap = new UnsafeBitmap(_bitmap);

            List<float> aEnergy = new List<float>() { 0.0f, 0.0f, 0.0f };
            List<float> aFactor = new List<float>();
            //int i = 0;
            for (int y = 0; y < bitmap.Height; y++)
            {
                for (int x = 0; x < bitmap.Width; x++)
                {
                    Color color = bitmap.GetPixel(x, y);

                    aEnergy[0] += color.R;
                    aEnergy[1] += color.G;
                    aEnergy[2] += color.B;
                }
            }

            for (int k = 0; k < 3; k++)
            {
                aFactor.Add(1.0f / aEnergy[k]);
            }

            float m = aFactor[0] + aFactor[1] + aFactor[2];
            for (int k = 0; k < 3; k++)
            {
                aFactor[k] *= 3.0f / m;
            }

            int nHeight = bitmap.Height;
            int nWidth = bitmap.Width;
            for (int y = 0; y < nHeight; y++)
            {
                for (int x = 0; x < nWidth; x++)
                {
                    Color color = bitmap.GetPixel(x, y);

                    float nR = color.R * aFactor[0];
                    float nG = color.G * aFactor[1];
                    float nB = color.G * aFactor[2];
                    if (nR > 255) nR = 255;
                    if (nG > 255) nG = 255;
                    if (nB > 255) nB = 255;
                    bitmap.SetPixel(x, y, Color.FromArgb((int)nR, (int)nG, (int)nB));
                }
            }
            bitmap.Dispose();
            MainFormSingleton.ActivePictureBox.Invalidate();
        }

        public static void Test2()
        {
            Bitmap _bitmap = (Bitmap)MainFormSingleton.ActivePictureBox.BackgroundImage;
            //BitmapFunctions.GetShift(bitmap, 0, 1);
            //new Deinterlace(DEINTERLACE.INTERPOLATE).Execute(bitmap);

            //new WhiteColorBalance().Execute(bitmap);
            //new OutlineEdges().Execute(bitmap);
            //new PrintedTextRegion().Execute(bitmap);

            Color color = Color.Transparent;


            new RoundColors(50).Execute(_bitmap).Dispose();
            Bitmap bitmap = _bitmap;

            int y = 0;
            int x = 0;

            int nWidth = bitmap.Width;
            int nHeight = bitmap.Height;

            UnsafeBitmap bitmapCloned = new UnsafeBitmap((Bitmap)_bitmap.Clone());
            for (y = 0; y < nHeight; y++)
            {
                Statistics histogramm = new Statistics(bitmapCloned, new Rectangle(0, y, _bitmap.Width, 1), 1, 1);
                histogramm.SortBy(PROCESSING_MODE.ColorCount);
                color = histogramm.ColorList[histogramm.ColorList.Count - 1].Key;
                for (x = 0; x < nWidth; x++)
                {
                    if (ColorFunctions.Distance(bitmap.GetPixel(x, y), color) < 2)
                    {
                        bitmap.SetPixel(x, y, Definitions.Black);
                    }
                    else
                    {
                        bitmap.SetPixel(x, y, Definitions.White);
                    }
                }
            }
            //bitmap.Dispose();
            MainFormSingleton.ActivePictureBox.Invalidate();
        }

        public static void Test()
        {
            UnsafeBitmap bitmap = MainFormSingleton.ActivePictureBox.BackgroundImage;
            int nHeight = bitmap.Height;
            int nWidth = bitmap.Width;
            for (int y = 0; y < nHeight; y++)
            {
                for (int x = 0; x < nWidth; x++)
                {
                    if (!(ColorFunctions.DistanceSquared(bitmap.GetPixel(x, y),Definitions.White)<10000))
                    {
                        bitmap.SetPixel(x, y, Definitions.Black);
                    }
                }
            }
            bitmap.Dispose();
            //FormGraduationCurves f = new FormGraduationCurves();
            //f.ShowDialog();
            //new Deinterlace().Execute(MainFormSingleton.ActivePictureBox.BackgroundImage).Dispose();
            //PerPixelFilterWhiteBigger200();

            //UnsafeBitmap bitmap = MainFormSingleton.ActivePictureBox.BackgroundImage;

            //int x = 250;
            //int y = 0;

            //bitmap.SetPixel(x, y, Definitions.Red);
            //BugFollower f = new BugFollower(bitmap, Definitions.Black);

            //List<Point> aPoint = f.Create(new Point(x, y));
            //bitmap.Dispose();
            //Graphics g = Graphics.FromImage(bitmap.InternalBitmap);
            //foreach (Point point in aPoint)
            //{
            //    g.DrawRectangle(new Pen(Brushes.Blue, 3), point.X, point.Y, 2, 2);
            //}


            //Debug.WriteLine(string.Format("{0}:{1}", cbTest.Name, "Test"));

            //------------------------------------------------------------------------------
            //new YCbCrFilter(new DoubleInterval(84, 245), new DoubleInterval(-26, -4), new DoubleInterval(2.9, 6.8)).Execute(MainFormSingleton.ActivePictureBox.BackgroundImage).Dispose();

            //MainFormSingleton.ActivePictureBox.BackgroundImage = imageFromFile;
            //Image imageFromFile = Image.FromFile(@"d:\temp\programmieren\temp\adac01.jpg");
            //new Lipschitz().Execute(MainFormSingleton.ActivePictureBox.BackgroundImage).Dispose();
            //------------------------------------------------------------------------------------

            //new ConnectedPixelLines().Execute(MainFormSingleton.ActivePictureBox.BackgroundImage).Dispose();

            //-----------------------------------------------------------------------------------

            //Bitmap _bitmap = (Bitmap)MainFormSingleton.ActivePictureBox.BackgroundImage;

            //Bitmap bitmapMask = new Bitmap((Bitmap)_bitmap.Clone());
            //new GrayScale().Execute(bitmapMask);

            //UnsafeBitmap bitmapMaskUnsafe = new UnsafeBitmap(bitmapMask);
            //for (int y = 0; y < bitmapMaskUnsafe.Height; y++)
            //{
            //    for (int x = 0; x < bitmapMaskUnsafe.Width; x++)
            //    {
            //        Color color = bitmapMaskUnsafe.GetPixel(x, y);
            //        if (color.R>150 && color.G>150 && color.B>150)
            //        {
            //            bitmapMaskUnsafe.SetPixel(x, y, Definitions.White);
            //        }
            //        else
            //        {
            //            bitmapMaskUnsafe.SetPixel(x, y, Definitions.Black);
            //        }
            //    }
            //}

            //bitmapMaskUnsafe.Dispose();

            //---------------------------------------------------------------------------------------
            //new Impainter(1, IMPAINTER_MODE.MANUALLY).Restore(_bitmap, bitmapMask);
            //---------------------------------------------------------------------------------------
            //new EnergyMap().Execute(_bitmap);
            //new Trajkovic().Execute((Bitmap)MainFormSingleton.ActivePictureBox.BackgroundImage);
            //new ColorPaletteMatching().Execute(_bitmap);

            //------------------------------------------------------------------------------------------
            /*Range range1 = new Range(0, 100, 10, Color.White);
            Range range2 = new Range(2, 100, 11, Color.White);
            bool bTrue = range1.Intersects(range2);

            //MainFormSingleton.ActivePictureBox.BackgroundImage = (Bitmap)Image.FromFile(@"D:\Temp\programmieren\Image Rec & Motion Detect\Bilder\barcode.jpg");
            Bitmap _bitmap = (Bitmap)MainFormSingleton.ActivePictureBox.BackgroundImage;

            ObjectExtractor objectExtractor = new ObjectExtractor(_bitmap, 3);
            objectExtractor.Prepare();
            List<BitmapObject> aBitmapObject = objectExtractor.ObjectsAsList;

            //new LowLevelGraphics.Filter.Experimental1().Execute(_bitmap);
            //new LowLevelGraphics.Filter.Experimental2().Execute(_bitmap);
            new Experimental3().Execute(_bitmap);*/

            //------------------------------------------------------------------------------------------------------------------------------
            MainFormSingleton.ActivePictureBox.Invalidate();
        }

        public static void ReadFromClipboard()
        {
            string sDisplayText = string.Empty;

            //Debug.WriteLine(string.Format("{0}:{1}", pasteFromClipboard.Name, "paste from clipboard"));
            if (Form1.ActiveForm == null)
            {
                FormChild formChild = GuiHelper.CreateNewChild();
                formChild.Activate();
                if (Form1.ActiveForm == null)
                {
                    return;
                }
            }

            //=====================================================================
            //Determine clipboard picture Data (BITMAP)
            Bitmap bitmap = Clipboard.GetData(DataFormats.Bitmap) as Bitmap;
            if (bitmap != null)
            {
                if (MainFormSingleton.ActivePictureBox != null)
                {
                    MainFormSingleton.ActivePictureBox.BackgroundImage = bitmap;
                    return;
                }
            }
            else
            {
                sDisplayText = "Clipboard contains no picture!";
            }

            //=====================================================================
            //Determine clipboard picture Data (URL)
            //URL
            string sText = Clipboard.GetData(DataFormats.Text) as string;
            Regex regex = new Regex(@"(\b(?:http|https|ftp|file)://[^\s]+)");
            if (regex.Match(sText).Success)
            {
                bitmap = (Bitmap)DownloadImageFromUrl(sText);
                int nCount = GetFormCount();
                if (nCount == 0)
                {
                    GuiHelper.CreateNewChild();
                }
            }

            if (bitmap != null)
            {
                if (MainFormSingleton.ActivePictureBox != null)
                {
                    MainFormSingleton.ActivePictureBox.BackgroundImage = bitmap;
                    return;
                }
            }
            else
            {
                sDisplayText = "Clipboard contains no url to load pic from!";
            }

            //if we get here show error
            MessageBox.Show(sDisplayText);
        }

        /// <summary>
        /// Download Image From URL
        /// </summary>
        /// <param name="imageUrl"></param>
        /// <returns></returns>
        public static Image DownloadImageFromUrl(string imageUrl)
        {
            Image image = null;

            try
            {
                HttpWebRequest webRequest = (System.Net.HttpWebRequest)HttpWebRequest.Create(imageUrl);
                webRequest.AllowWriteStreamBuffering = true;
                webRequest.Timeout = 30000;

                System.Net.WebResponse webResponse = webRequest.GetResponse();

                Stream stream = webResponse.GetResponseStream();

                image = Image.FromStream(stream);

                webResponse.Close();
            }
            catch (Exception ex)
            {
                return null;
            }

            return image;
        }

        /// <summary>
        /// Get Form Count
        /// </summary>
        /// <param name="nCount"></param>
        /// <returns></returns>
        public static int GetFormCount()
        {
            int nCount = 0;
            foreach (Form form in Application.OpenForms)
            {
                if (form.GetType() == typeof(FormChild))
                {
                    nCount++;
                }
            }
            return nCount;
        }

        public static void AlignFromLeft()
        {
            int nLeft = 0;
            foreach (Form form in MainFormSingleton.Instance.MdiChildren)
            {
                FormChild formChild = form as FormChild;
                if (formChild == null) continue;
                formChild.Left = nLeft;
                nLeft += formChild.Width;
            }
        }

        public static void SetToWidth()
        {
            foreach (Form form in MainFormSingleton.Instance.MdiChildren)
            {
                FormChild formChild = form as FormChild;
                if (formChild == null) continue;
                form.Width = formChild.pictureBox1.BackgroundImage.Width;
                form.Dock = DockStyle.None;
            }
        }

        public static void AlignAllWindows()
        {
            foreach (Form form in MainFormSingleton.Instance.MdiChildren)
            {
                FormChild formChild = form as FormChild;
                if (formChild == null) continue;
                formChild.Top = 0;
            }
        }

        public static void SetAllWindowsToImageSize()
        {
            foreach (Form form in MainFormSingleton.Instance.MdiChildren)
            {
                FormChild formChild = form as FormChild;
                if (formChild == null) continue;
                form.Size = formChild.pictureBox1.BackgroundImage.Size;
                form.Dock = DockStyle.None;
            }
        }

        public static void SetAllMDIChildsFormWindowState(FormWindowState _formWindowState)
        {
            foreach (Form form in MainFormSingleton.Instance.MdiChildren)
            {
                form.WindowState = _formWindowState;
            }
        }

        public static void base64FL2IBarcode()
        {
            System.Windows.Forms.OpenFileDialog fd = new System.Windows.Forms.OpenFileDialog();
            if (fd.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            //            try
            //            {
            StreamReader reader = new StreamReader(fd.FileName);
            string sFileToDecode = reader.ReadToEnd();
            DecodeBarcodePictureFromString(sFileToDecode);
            //}
            /*            catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }*/
        }

        /// <summary>
        /// DecodeBarcodePictureFromString - use this to decode
        /// </summary>
        /// <param name="_sFileToDecode">This is the file to load</param>
        /// <remarks>Use this only for flexstor II code</remarks>
        public static void DecodeBarcodePictureFromString(string _sFileToDecode)
        {
            int x = 0;
            int y = 0;
            int nHeight = 1;

            byte[] aByte = Decode(_sFileToDecode);
            int nWidth = aByte.Length;
            UnsafeBitmap bitmap = new UnsafeBitmap(new Bitmap(nWidth, nHeight));

            int i = 0;
            for (y = 0; y < nHeight; y++)
            {
                for (x = 0; x < nWidth; x++)
                {
                    bitmap.SetGrayPixel(x, y, aByte[i]);
                    i++;
                }
            }

            bitmap.Dispose();
            MainFormSingleton.ActivePictureBox.BackgroundImage = new Bitmap(bitmap.InternalBitmap, new Size(nWidth, 500));
            MainFormSingleton.ActivePictureBox.Invalidate();
        }

        public static byte[] Decode(string str)
        {
            byte[] decbuff = Convert.FromBase64String(str);
            return decbuff;
        }

        public static void ExtractLeftRightInterlaced()
        {
            Deinterlace deinterlace = ExtractEvenOddInterlaced();
            deinterlace.BitmapOdd.Dispose();
            deinterlace.BitmapEven.Dispose();

            MainFormSingleton.ActivePictureBox.BackgroundImage = deinterlace.BitmapEven.InternalBitmap;
            FormChild formChild = GuiHelper.CreateNewChild();

            MainFormSingleton.ActivePictureBox.BackgroundImage = deinterlace.BitmapOdd.InternalBitmap;
        }

        /// <summary>
        /// Deinterlace
        /// </summary>
        /// <returns></returns>
        public static Deinterlace ExtractEvenOddInterlaced()
        {
            Deinterlace deinterlace = new Deinterlace(DEINTERLACE.HORIZONTAL);
            deinterlace.Execute(MainFormSingleton.ActivePictureBox.BackgroundImage);
            return deinterlace;
        }

        public static void InterlacedToAnaglyph()
        {
            Deinterlace deinterlace = ExtractEvenOddInterlaced();
            Anaglyph anaglyph = new Anaglyph();
            anaglyph.Mode = AnaglyphMode.Optimized;
            UnsafeBitmap bitmapResult = anaglyph.Process(deinterlace.BitmapEven, deinterlace.BitmapOdd);
            bitmapResult.UnlockImage();
            MainFormSingleton.ActivePictureBox.BackgroundImage = bitmapResult.InternalBitmap;

            deinterlace.BitmapEven.Dispose();
            deinterlace.BitmapOdd.Dispose();
        }

        public static void ImageStatistics()
        {
            Form formImageStatistics = new FormStatistics(MainFormSingleton.ActivePictureBox.BackgroundImage);
            formImageStatistics.MdiParent = MainFormSingleton.Instance;
            formImageStatistics.Show();
        }

        /// <summary>
        /// Composings the specified _filter.
        /// </summary>
        /// <param name="_filter">The _filter.</param>
        public static void Composing(ITwoSourceFilter _filter)
        {
            Image mainFormSingletonActivePictureBoxBackgroundImage = MainFormSingleton.ActivePictureBox.BackgroundImage;
            FormChildList childList = new FormChildList();
            if (childList.ShowDialog() != DialogResult.OK) return;
            FormItem item = childList.FormItem;
            Image image = item.Form.pictureBox1.BackgroundImage;
            if (image == mainFormSingletonActivePictureBoxBackgroundImage)
            {
                MessageBox.Show("Please choose different pictures", "Result");
                return;
            }
            UnsafeBitmap bitmap = new NAnd().Process(mainFormSingletonActivePictureBoxBackgroundImage, image);
            bitmap.Dispose();
            MainFormSingleton.ActivePictureBox.BackgroundImage = bitmap.InternalBitmap;
        }

        public static void OriginalSize()
        {
            Debug.WriteLine("Original size");
            MainFormSingleton.ActivePictureBox.BackgroundImageLayout = ImageLayout.Center;
            MainFormSingleton.ActivePictureBox.Invalidate();
            Bitmap bitmap = (Bitmap)MainFormSingleton.ActivePictureBox.BackgroundImage;
        }

        /// <summary>
        /// New Window Last Loaded
        /// </summary>
        public static void NewWindowLastLoaded()
        {
            //Debug.WriteLine(string.Format("{0}:{1}", newWindowlastLoadedToolStripMenuItem.Name, "new window last loaded"));
            Image mainFormSingletonActivePictureBoxBackgroundImageClone = Image.FromFile(MainFormSingleton.ActiveFormChild.LoadedPictureFullQualifiedPath);
            FormChild child = GuiHelper.CreateNewChild();
            child.pictureBox1.BackgroundImage = mainFormSingletonActivePictureBoxBackgroundImageClone;
        }

        /// <summary>
        /// New Window Open Copy
        /// </summary>
        public static void NewWindowOpenCopy()
        {
            //Debug.WriteLine(string.Format("{0}:{1}", newWindowopenCopyToolStripMenuItem.Name, "new window open copy"));
            Image mainFormSingletonActivePictureBoxBackgroundImageClone = (Image)MainFormSingleton.ActivePictureBox.BackgroundImage.Clone();
            FormChild child = GuiHelper.CreateNewChild();
            child.pictureBox1.BackgroundImage = mainFormSingletonActivePictureBoxBackgroundImageClone;
        }

        public static void ExecuteLambdaFilter()
        {
            UnsafeBitmap bitmap = MainFormSingleton.ActivePictureBox.BackgroundImage;
            try
            {
                ExecuteLambdaFilter(bitmap);
            }
            catch (Exception ex)
            {
                bitmap.Dispose();
                if (ex.InnerException != null)
                {
                    MessageBox.Show(ex.InnerException.Message);
                }
                else
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        /// <summary>
        /// Executes the lambda filter.
        /// </summary>
        /// <param name="_bitmap">The _bitmap.</param>
        /// <returns></returns>
        public static UnsafeBitmap ExecuteLambdaFilter(UnsafeBitmap _bitmap)
        {
            new Lambda(MainFormSingleton.Instance.toolStripComboBox1.Text).Execute(_bitmap).Dispose();
            MainFormSingleton.ActivePictureBox.Invalidate();
            return _bitmap;
        }

        public static void ShowImageInfo()
        {
            Form formImageInfo = new FormImageInfo(MainFormSingleton.ActivePictureBox.BackgroundImage);
            formImageInfo.MdiParent = MainFormSingleton.Instance;
            formImageInfo.Show();
        }

        public static void CopyFromActiveToAll()
        {
            Image image = (Image)MainFormSingleton.ActivePictureBox.BackgroundImage;
            if (image == null) return;
            foreach (Form form in MainFormSingleton.Instance.MdiChildren)
            {
                ((FormChild)form).pictureBox1.BackgroundImage = (Image)MainFormSingleton.ActivePictureBox.BackgroundImage.Clone();
            }
        }

        public static void CloseAllChilds()
        {
            foreach (Form form in MainFormSingleton.Instance.MdiChildren)
            {
                form.Close();
            }
        }

        public static void CloseAllChildsButActive()
        {
            foreach (Form form in MainFormSingleton.Instance.MdiChildren)
            {
                if (form != MainFormSingleton.Instance.ActiveMdiChild) form.Close();
            }
        }
    }
}
